package com.pride1952.myoptimusx3;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class PlusActivity extends Activity {
    private String TAG = "PlusActivity";
    public static final int ICON_CHANGED = 1;
    public static final int ICON_NOTCHANGE =0;

    private ListView iconListView;
    private PlusAdapter plusAdapter;
    private List<PlusItem> itemList = new ArrayList<PlusItem>();
    private Button sendButton;
    private Button backButton;
    private EditText sendMsg;
    private List<String> iconNameList = new ArrayList<String>();
    private int ifIconChange = ICON_NOTCHANGE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plus);

        sendButton = (Button) findViewById(R.id.plus_input_send);
        backButton = (Button) findViewById(R.id.plus_back);
        sendMsg = (EditText) findViewById(R.id.plus_input_text);

        initIcons();
        plusAdapter = new PlusAdapter(PlusActivity.this, R.layout.plus_item, itemList);
        iconListView = (ListView) findViewById(R.id.plus_list_view);
        iconListView.setAdapter(plusAdapter);
        iconListView.requestFocus();

        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("ifIconChange", ifIconChange);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(PlusActivity.this, "hi", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * Adapter类
     * */
    public class PlusAdapter extends ArrayAdapter<PlusItem> {

        private int resourceId;     //layout的id

        public PlusAdapter(Context context, int textViewResourceId, List<PlusItem> objects){
            super(context, textViewResourceId, objects);
            resourceId = textViewResourceId;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final PlusItem plusItem = getItem(position);
            final int plusItemType = plusItem.getType();
            View view;
            ViewHolder viewHolder;
            if(convertView == null){
                view = LayoutInflater.from(getContext()).inflate(resourceId, null);
                viewHolder = new ViewHolder();
                viewHolder.leftLayout = (LinearLayout) view.findViewById(R.id.plus_left_layout);
                viewHolder.rightLayout = (LinearLayout) view.findViewById(R.id.plus_right_layout);
                viewHolder.imageView = (ImageView) view.findViewById(R.id.plus_image);
                viewHolder.title = (TextView) view.findViewById(R.id.plus_title);
                viewHolder.content = (TextView) view.findViewById(R.id.plus_content);
                viewHolder.button = (Button) view.findViewById(R.id.plus_button);
                view.setTag(viewHolder);
            }
            else{
                view = convertView;
                viewHolder = (ViewHolder) view.getTag();
            }
            viewHolder.imageView.setImageResource(plusItem.getImgId());
            viewHolder.title.setText(plusItem.getTitle());
            viewHolder.content.setText(plusItem.getContent());
            if(plusItemType > PlusItem.TYPE_NOTADD){
                viewHolder.button.setBackgroundResource(R.mipmap.heart_yes_red);
            }
            else{
                viewHolder.button.setBackgroundResource(R.mipmap.heart_no);
            }
            viewHolder.button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(plusItem.getType() == PlusItem.TYPE_NOTADD){     //动作为添加icon
                        addWebTitle(plusItem);
                    }
                    else{                                               //动作为移除icon
                        removeWebTitle(plusItem, plusItemType);
                    }
                    notifyDataSetChanged();         //更新listView
                }
            });
            viewHolder.leftLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(webSite.getSite(plusItem.getTitle())));
                    startActivity(intent);
                }
            });
            return view;
        }

        class ViewHolder{
            LinearLayout leftLayout;
            LinearLayout rightLayout;
            ImageView imageView;
            TextView title;
            TextView content;
            Button button;
        }
    }

    /**
     * ListView子项item的按钮添加事件，将当前plusItem添加至快捷入口
     * @param plusItem  需要添加的子项item
     */
    private void addWebTitle(PlusItem plusItem){
        SharedPreferences sharedPref = getSharedPreferences("quickIcon", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        int iconCount = sharedPref.getInt("iconCount", 0);
        Log.d(TAG, "addWebTitle iconCount: " + iconCount);
        if(iconCount++ >= webSite.MAX_ICONS){          //需判断是否icon数量超过上限
            Toast.makeText(PlusActivity.this, "快捷入口只能有7个啦@>_<@", Toast.LENGTH_SHORT).show();
        }
        else
        {
            Log.d(TAG, "iconCount_ADDED: " + iconCount);
            editor.putInt("iconCount", iconCount);
            editor.putString(iconCount+"", plusItem.getTitle());
            editor.commit();
            Toast.makeText(PlusActivity.this, "已添加"+ plusItem.getTitle() +"至快捷入口", Toast.LENGTH_SHORT).show();
            boolean b = plusItem.changeTypeToADDED(iconCount);
            Log.d(TAG, "addWebTitle changeTypeToADDED= " + b);
            ifIconChange = ICON_CHANGED;        //快捷入口改变的标志位
        }
    }

    /**
     * ListView子项item的按钮移除事件，将当前plusItem从快捷入口移除
     * @param plusItem  需要移除的子项item
     * @param itemType  子项item在sharedPref中的状态码
     */
    private void removeWebTitle(PlusItem plusItem, int itemType){
        SharedPreferences sharedPref = getSharedPreferences("quickIcon", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        int iconCount = sharedPref.getInt("iconCount", 0);
        if(iconCount <= webSite.MIN_ICONS){          //需判断是否icon数量低于下限
            Toast.makeText(PlusActivity.this, "再删就没啦@>_<@", Toast.LENGTH_SHORT).show();
        }
        else{
            editor.remove(itemType+"");
            for(int i = itemType; i < iconCount; i++){
                String webTitle = sharedPref.getString(i+1+"", null);
                editor.putString(i+"", webTitle);
            }
            editor.putInt("iconCount", --iconCount);
            editor.commit();
            Toast.makeText(PlusActivity.this, "已将" +plusItem.getTitle() +"从快捷入口移除", Toast.LENGTH_SHORT).show();
            boolean b = plusItem.changeTypeToNOTADD();
            Log.d(TAG, "removeWebTitle changeTypeToNOTADD= " + b);
            ifIconChange = ICON_CHANGED;
        }
    }

    /**
     * 初始化所有的图标
     * */
    private void initIcons(){
        iconNameList = webSite.getAllIconList();
        PlusItem item;
        //todo 修改为使用迭代器来遍历List
        for(int i = 0; i < iconNameList.size(); i++){       //生成已有网站的所有item压入itemList
            String webTitle = iconNameList.get(i);
            Log.d(TAG, "initIcons webTitle= " + webTitle);
            item = new PlusItem(webTitle, webSite.getContent(webTitle),
                    webSite.getImageId(webTitle), getWebTitleType(webTitle));
            itemList.add(item);
        }
    }
    /**
     * 获取当前Item的Type
     * 根据sharedPref已有的值来判断当前webTitle是否已添加至快捷入口
     * @param webTitle 需判断Type值的名称，eg:微博，人人
     * @return Type=0表示未添加至快捷入口，Type=1~7表示已添加至快捷入口，并链接至imgbtn_quick1~imgbtn_quick7
     * */
    private int getWebTitleType(String webTitle){
        SharedPreferences sharedPref = getSharedPreferences("quickIcon", MODE_PRIVATE);
        int iconCount = sharedPref.getInt("iconCount", 0);
        for(int i = 1; i <= iconCount; i++){
            if(webTitle.equals(sharedPref.getString(i+"", null))){
                Log.d(TAG, "getItemType webName= " + webTitle +"; Type_Added= " + i);
                return i;
            }
        }
        Log.d(TAG, "getItemType webName= " + webTitle +"; Type_NotAdd");
        return PlusItem.TYPE_NOTADD;
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra("ifIconChange", ifIconChange);
        setResult(RESULT_OK, intent);
        finish();
    }
}
